<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Like
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: RemoteController.php 2010-09-07 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Like
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Like_RemoteController extends Core_Controller_Action_Standard
{
  
	public function init() 
	{
    $this->_helper->layout->disableLayout();
    $this->view->error = 0;
    $this->view->html = '';

    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->subject = $subject = Engine_Api::_()->getItem((string)$this->_getParam('object'), (int)$this->_getParam('object_id'));
    
    if (!$viewer->getIdentity()){
      $this->view->error =  3;
      $this->view->html =  Zend_Registry::get('Zend_Translate')->_('like_LIKE_LOGIN_ERROR');
      return ;
    }

    if ($this->_getParam('object') == 'user'){
      if (!Engine_Api::_()->getApi('settings', 'core')->getSetting('like.profile.enabled', 1)){
        $this->view->error = 1;
        $this->view->html = Zend_Registry::get('Zend_Translate')->_('like_LIKE_ADMIN_TURN_OFF_ERROR');
        return ;
      }
    }

    if (!Engine_Api::_()->authorization()->isAllowed('like', null, 'create')){
      $this->view->error = 2;
      $this->view->html = Zend_Registry::get('Zend_Translate')->_('like_LIKE_ADMIN_TURN_OFF_ERROR');
      return ;
    }

    $this->view->viewer_url = $viewer->getHref();
	}
	
	public function likeAction() 
	{
    if ($this->view->error){
      return ;
    }
    
    $subject = $this->view->subject;
    $viewer = $this->view->viewer;

		if (Engine_Api::_()->like()->like($subject)){
			$activityApi = Engine_Api::_()->getDbtable('actions', 'activity');
      $action = $activityApi->addActivity($viewer, $subject, 'like');
      $activityApi->attachActivity($action, $subject);
		}else{
			$this->view->error = 5;
			$this->view->html = Zend_Registry::get('Zend_Translate')->_('like_LIKE_UNDEFINED_ERROR');
		}

    $this->view->viewer = $viewer->toArray();
    $this->view->subject = $subject->toArray();
	}
	
	public function unlikeAction() 
	{
    if ($this->view->error){
      return ;
    }
    
    $subject = $this->view->subject;
    $viewer = $this->view->viewer;
    
		if (!Engine_Api::_()->like()->unlike($subject)){
			$this->view->error = 5;
			$this->view->html = Zend_Registry::get('Zend_Translate')->_('like_UNLIKE_UNDEFINED_ERROR');
		}

    $this->view->viewer = $viewer->toArray();
    $this->view->subject = $subject->toArray();
	}

}